import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

"""
第一个神经网络模型
"""
if __name__ == "__main__":

    # 将数组转化为矩阵
    x_data = np.linspace(-0.5, 0.5, 500)[:, None]

    noise_data = np.random.uniform(-0.01, 0.02, x_data.shape)
    y_data = np.square(x_data) + noise_data

    # 声明初始化变量
    x = tf.placeholder(tf.float32, [None, 1])
    y = tf.placeholder(tf.float32, [None, 1])

    # 声明第一层神经网络   矩阵相乘注意行列关系
    weight_L1 = tf.Variable(tf.random_normal([1, 10]))
    basic_L1 = tf.Variable(tf.zeros([1, 10]))
    publish_L1 = tf.nn.tanh(tf.matmul(x, weight_L1) + basic_L1)

    # 第二层神经网络    矩阵相乘和输出矩阵类型
    weight_L2 = tf.Variable(tf.random_normal([10, 1]))
    basic_L2 = tf.Variable(tf.zeros([1, 1]))
    publish_L2 = tf.nn.tanh(tf.matmul(publish_L1, weight_L2) + basic_L2)

    # 定义训练误差标准
    train = tf.train.GradientDescentOptimizer(0.2).minimize(tf.reduce_mean(tf.square(publish_L2 - y)))
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        # 训练1000次
        for i in range(1, 8000):
            sess.run(train, feed_dict={x: x_data, y: y_data})

        # 得到模型的预测值y
        prediction_value = sess.run(publish_L2, {x: x_data})
        plt.figure()
        plt.plot(x_data, prediction_value, c="r")
        plt.scatter(x_data, y_data)
        plt.show()
